import sdk from 'sdk'
import { doPay } from 'api'
import ua from './ua'
import cashierSDK from './cashier.sdk.js'
import { getFullUrl } from 'utils/helper/query'
import ENV from 'utils/env'

function sdkPay(params, callback, callbackUrl, payCancelUrl) {
  if (ua.isAppWebview) { // appwebview
    sdk.payOrderSDK({
      merchantNo: params.merchantNo,
      merchantOrderNo: params.merchantOrderNo,
      token: params.token,
      mebid: params.mebId,
      remark: params.remark,
      subject: params.orderTitle,
      callbackUrl: callbackUrl,
      payCancelUrl: payCancelUrl,
      notifyUrl: params.notifyUrl,
      totalAmount: params.payMoney,
      orderNo: params.orderNo,
      isNeedShowTime: true,
      leftTime: params.validTime
    }).then(res => {
      // ios该回调未执行，不能依赖该回调处理业务逻辑
      console.log('payOrderSDK finish', res)
    }).catch(err => {
      console.log(JSON.stringify(err, 'err'))
    })

    console.log('-------------ready callback')

    callback && callback()
  } else { // [TODO] 该路径暂时留给公众号h5
    const payParams = {
      env: ENV, // [TODO] local环境要转成dev环境
      merchantNo: params.merchantNo,
      merchantOrderNo: params.merchantOrderNo,
      token: params.token,
      mebid: params.mebid,
      subject: params.orderTitle,
      totalFee: params.payMoney,
      notifyUrl: params.notifyUrl,
      versions: 'MDT',
      callbackUrl: params.callbackUrl,
      // paymentDes1: '订单编号：' + params,
      payCancelUrl: params.payCancelUrl
    }
    //释放导航栏控制 否则收银台无法返回
    // looseTitleControl()
    cashierSDK.setOptions(payParams)
  }
}

/**
 * 
 * @param {String} orderNo 订单号
 * @param {Boolean} pageMode 页面跳转模式 replace:替换 navigate:跳转
 * @param {Function} callback 拉起支付后回调
 */
export default function (orderNo, pageMode = 'replace', callback) {
  // #ifdef H5
  // 请求支付接口成功后拉取支付
  doPay(orderNo).then(payRes => {
    try {
      if (payRes && payRes.code === 0) {
        // 初始化参数
        const payResultInfo = JSON.parse(payRes.result.formContent)
        payResultInfo.orderNo = orderNo  

        // 跳转链接  
        let url = '' // 跳转到支付结果页        
        let payCancelUrl = '' // 支付失败调到原来页面
        url = getFullUrl(`/packageOrder/pages/booking-result/index?status=1&orderNo=${orderNo}`)
        payCancelUrl = getFullUrl(`/packageOrder/pages/booking-result/index?status=0&orderNo=${orderNo}`)        
        sdkPay(payResultInfo, callback, url, payCancelUrl)
      } else {
        this.createOrderFlag = false
      }
    } catch (err) {
      console.log('err', err)
    }
  })
  // #endif

  // #ifdef MP
  console.log('ua.isMP:', sdk)
  let url = '/packageOrder/pages/cashier/index?orderNo='+orderNo
  if (pageMode === 'replace') {
    sdk.redirectTo({
      url: url
    })
  } else {
    sdk.navigateTo({
      url: url
    })
  }
  // #endif
}